//
//  KLSGRankingListViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGRankingListViewController.h"
#import "KLSGRankingListModel.h"
#import "KLSGFirstKResultsModel.h"
#import "KLSGRankingListCell.h"
#import "KLSGProgramAndSpeakController.h"
#import "KLSGSpeakController.h"
#import "KLSGDataFail.h"

@interface KLSGRankingListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

//  数据数组
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) NSMutableArray *twoArray;
@property (nonatomic, strong) NSMutableArray *headerArray;

@property (nonatomic, strong) KLSGDataFail *faliView;
@end

@implementation KLSGRankingListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    if (self.dataDic.count == 0) {
        [self setUpData];
    }
}

#pragma mark -- 解析数据
- (void)setUpData
{
    [self.faliView hidden];
    //  1.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    //  2.创建网址对象
    NSURL *url = [NSURL URLWithString:kRankingListUrl];
    //  3.根据网址对象创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    //  4.建立回话
    __block KLSGRankingListViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic valueForKey:@"datas"];
            mySelf.dataDic = [NSMutableDictionary dictionary];
            mySelf.headerArray = [NSMutableArray array];
            for (NSDictionary *di in array) {
                NSArray *arra = [di valueForKey:@"list"];
                [mySelf.headerArray addObject:[di valueForKey:@"title"]];
                //  两个
                NSMutableArray *tempArray = [NSMutableArray array];

                for (NSDictionary *d in arra) {
                    KLSGRankingListModel *model = [[KLSGRankingListModel alloc] init];
                    [model setValuesForKeysWithDictionary:d];
                    
                    mySelf.twoArray = [NSMutableArray array];
                    for (NSDictionary *firstRDic in model.firstKResults) {
                        KLSGFirstKResultsModel *firstRModel = [[KLSGFirstKResultsModel alloc] init];
                        [firstRModel setValuesForKeysWithDictionary:firstRDic];
                        [self.twoArray addObject:firstRModel];
                    }

                    NSArray *smallArray = [d valueForKey:@"firstKResults"];
                    NSDictionary *smallDic = smallArray[1];
                    NSString *string = [smallDic valueForKey:@"title"];
                    [mySelf.twoArray addObject:string];
                    [tempArray addObject:model];

                }
                [mySelf.dataDic setValue:tempArray forKey:[di valueForKey:@"title"]];
            }
            [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
        } else {
            NSLog(@"解析失败");
            [mySelf performSelectorOnMainThread:@selector(failload) withObject:nil waitUntilDone:NO];
        }
    }];
    //  6.  启动解析
    [task resume];
}
- (KLSGDataFail *)faliView
{
    if (!_faliView) {
        _faliView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 150, kScreenWidth, 300)];
    }
    return _faliView;
}
- (void)failload
{
    
    [self.faliView netRequestFailWithBlock:^{
        [self.faliView hidden];
        [self setUpData];
    }];
    [self.tableView addSubview:self.faliView];
}

- (void)reloadData:(UITableView *)tableView
{
    [tableView reloadData];
}

- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    [self.view addSubview:self.tableView];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self tableHeaderView];
}
- (void)tableHeaderView
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 190)];
//    imageView.backgroundColor = [UIColor yellowColor];
    imageView.image = [UIImage imageNamed:@"PankingListPic"];
    self.tableView.tableHeaderView = imageView;
}


#pragma mark -- tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.dataDic allKeys].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifire = @"rankCell";
    KLSGRankingListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifire];
    if (cell == nil) {
        cell = [[KLSGRankingListCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifire];
        
    }
    
    NSString *headerString = self.headerArray[indexPath.section];
    NSArray *tempArray = [self.dataDic valueForKey:headerString];
    
    KLSGRankingListModel *model = tempArray[indexPath.row];
    cell.titleLable.text = model.title;
    [cell.coverPathImageView sd_setImageWithURL:[NSURL URLWithString:model.coverPath] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    cell.firstTitleLable.text = [NSString stringWithFormat:@"1. %@", model.firstTitle];
    cell.twoTitleLable.text = [NSString stringWithFormat:@"2. %@", model.firstKResults[1][@"title"]];

    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return self.headerArray[section];
}
//  点击cell跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *titleString = self.headerArray[indexPath.section];
    NSArray *array = [self.dataDic valueForKey:titleString];
    KLSGRankingListModel *model = array[indexPath.row];
    KLSGProgramAndSpeakController *CANVC = [[KLSGProgramAndSpeakController alloc] init];
    CANVC.index = indexPath.row;
    CANVC.section = indexPath.section;
    CANVC.keyString = model.key;
    CANVC.titleString = model.title;
    CANVC.contentTypeString = model.firstKResults[1][@"contentType"];
    [self.navigationController pushViewController:CANVC animated:YES];
    
//    if (indexPath.section == 0) {
//        KLSGProgramAndSpeakController *CANVC = [[KLSGProgramAndSpeakController alloc] init];
//        CANVC.index = indexPath.row;
//        CANVC.section = indexPath.section;
//        CANVC.keyString = model.key;
//        CANVC.titleString = model.title;
//        CANVC.contentTypeString = model.firstKResults[1][@"contentType"];
//        [self.navigationController pushViewController:CANVC animated:YES];
//    } else {
//        KLSGSpeakController *speskVC = [[KLSGSpeakController alloc] init];
//        speskVC.keyString = model.key;
//        speskVC.titleString = model.title;
//        speskVC.contentTypeString = model.firstKResults[1][@"contentType"];
//
//        [self.navigationController pushViewController:speskVC animated:YES];
//    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
